package day_2022_9_to_12.Day;

import java.util.HashMap;
import java.util.Map;

/**
 * @author haomin
 * @date 2022/10/13 17:21
 **/
public class Day41_2_Num219_ContainsNearbyDuplicate {
    class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            for(int i = 0; i < nums.length-1; ++i){
                int j = i + 1;
                while(j < nums.length && (j-i) <= k){
                    if(nums[i] == nums[j]) return true;
                    j++;
                }
            }
            return false;
        }
    }
    class Solution2 {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            Map<Integer, Integer> map = new HashMap<>();
            for(int i = 0; i < nums.length; ++i){
                if(map.containsKey(nums[i])){
                    if((i - map.get(nums[i]) <= k)) return true;
                }
                // 覆盖之后的位置和下一个相同值肯定离得更近
                map.put(nums[i], i);
            }
            return false;
        }
    }
}